package com.gs.netty.core.utils;

import io.netty.channel.Channel;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;

public class WebSocketChannelContextUtils {


    /**
     * 获取属性
     * @param channel
     * @param name
     * @return
     */
    public static Object getAttribute(Channel channel, String name) {
        return getAttribute(channel,name, Object.class);
    }


    /**
     * 获取属性
     * @param channel
     * @param name
     * @return
     */
    public static <T> T getAttribute(Channel channel, String name,Class<T> requiredType) {
        AttributeKey<T> attribute = AttributeKey.valueOf(name);
        Attribute<T> attr = channel.attr(attribute);
        return attr == null? null : attr.get();
    }

    /**
     * 设置属性
     * @param channel
     * @param name
     * @param value
     */

    public static void setAttribute(Channel channel, String name, Object value) {
        channel.attr(AttributeKey.valueOf(name)).set(value);
    }


    /**
     * 设置用户信息
     * @param channel
     * @param value
     */
    public static void setUserInfoAttribute(Channel channel, Object value) {


        setAttribute(channel,  channel.id().asShortText(), value);
    }

    /**
     * 获取用户信息
     * @param channel

     */
    public static Object getUserInfoAttribute(Channel channel) {
      return  getAttribute(channel, channel.id().asLongText());
    }
}
